package com.example.game;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.io.File;

import static com.example.game.GamePage.databaseHelper;
import static com.example.game.GamePage.player;


//在运行了GamePage类中 onCreate()方法内的 setDataPath()之后才能正常使用

//读取存档和新建存档，都只有在进入GamePage的时候才需要调用，所以不用放在DatabaseHelper类中

public class DatabaseHelper {
    String TAG = "databaseHelperTAG";
    DatabaseHelper(){
        Log.d(TAG, "DatabaseHelper: DO NOTHING");
    }

    public SQLiteDatabase getDataBase(){
        Log.d(TAG, "onCreateDatabase: checkpoint 2");
    //    String DATA_PATH = GamePage.getFilesDir().getPath() + "data/"+getPackageName()+"/databases";
    //    String DATA_PATH = "/data/data/com.example.game/databases";
        Log.d(TAG, player.DATA_PATH);
        File dbFile = new File(player.DATA_PATH);
        boolean t = dbFile.mkdirs();
        if(t){
            Log.d(TAG, "mkdir successed");
        }else{
            Log.d(TAG, "mkdir failed");
        }
        Log.d(TAG, "onCreateDatabase: checkpoint 3");
        Log.d(TAG, "getDataBase: DATA_PATH = " + player.DATA_PATH);
        final SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(player.DATA_PATH + "/PlayerInfo.db",null);
        Log.d(TAG, "onCreateDatabase: checkpoint 4 : create database finished");
        //完成实例化SQLiteDatabase
        return db;
    }

    public void saveGame(){
        Log.d(TAG, "onSave: checkpoint 1");
        SQLiteDatabase db = getDataBase();
        Log.d(TAG, "onSave: checkpoint 2");
        String sql_cmd = "";
        sql_cmd = "insert into user values(?";
        for(int i = 0 ; i < player.BUILDING_TYPE_COUNT ; i++ ){
            sql_cmd = sql_cmd + ",?";
        }
        sql_cmd = sql_cmd + ")";
        Log.d(TAG, sql_cmd);
        for(int i = 1; i < player.BUILDING_TYPE_COUNT + 1 ; i ++){
            Log.d(TAG, "Init_Saved_Game: building_list[0]["+String.valueOf(i-1)+"] = "+String.valueOf(player.building_list[0][i-1]));
        }
        //新生成一个完整的数组，用来放进execSQL函数中的Object[]
        Object[] exec = new Object[21];
        exec[0] = player.cash;
        for(int i = 1; i < player.BUILDING_TYPE_COUNT + 1 ; i++){
            exec[i] = player.building_list[0][i-1];
        }
        db.execSQL(sql_cmd,exec);
    }

    public int getDatabaseCount(SQLiteDatabase db){
        String databaseTAG = "databaseTAG";
        String sql_cmd = "select count(*) from user";
        Cursor cursor_count = db.rawQuery(sql_cmd, null);
        Log.d(databaseTAG, "cursor_count created");
        cursor_count.moveToFirst();
        int count = cursor_count.getInt(0);
        cursor_count.close();
        Log.d(databaseTAG, "cursor_count closed");
        Log.d(databaseTAG, "count : " + Long.toString(count));
        return count;
    }

    public void loadGame(){
        SQLiteDatabase db = getDataBase();
        int count = getDatabaseCount(db);

        Cursor cursor = db.query("user",null,null,null,null,null,null);
        cursor.moveToFirst();
        String TAG = "loading_TAG";
        Log.d(TAG, "record existed ");
        while(count > 1){           //i have no idea why it works, but it works anyway
            cursor.moveToNext();
            count -- ;
        }
        Log.d(TAG, "Init_Saved_Game: total column number is " + String.valueOf(cursor.getColumnCount()));
        player.cash = cursor.getLong(0);
        Log.d(TAG, "Init_Saved_Game: record 1 finish");
        for(int i = 1; i < player.BUILDING_TYPE_COUNT + 1 ; i ++){
            player.building_list[0][i-1] = cursor.getLong(i);
            Log.d(TAG, "Init_Saved_Game: building_list[0]["+String.valueOf(i-1)+"] = "+String.valueOf(player.building_list[0][i-1]));
            player.building_list[1][i-1] = player.building_orignal_price[i-1];
            for(int j = 0; j < player.building_list[0][i-1] ; j++){
                player.building_list[1][i-1] *= 1.15;
            }
        }
        Log.d(TAG, "Init_Saved_Game: record 2 finish");
        player.refresh_production();
        cursor.close();
    }

    public void make_save_file(){
        SQLiteDatabase db = databaseHelper.getDataBase();
        String databaseTAG = "dbhelper.make_save_file";
        

        Cursor cursor_for_sqlmaster = db.query("sqlite_master", null, null, null, null, null, null);


        String sql_cmd = "";
        Boolean sql_is_empty = cursor_for_sqlmaster.moveToFirst();
        while (!cursor_for_sqlmaster.getString(1).equals("user")) {
            Log.d(databaseTAG, "searching sqlite_master... " + cursor_for_sqlmaster.getString(1));
            if (!cursor_for_sqlmaster.moveToNext()) {
                Log.d(databaseTAG, "table\"user\"not existed");
                sql_cmd = "create table user(cash_saved INT";
                for (int i = 1; i < player.BUILDING_TYPE_COUNT + 1; i++) {
                    sql_cmd = sql_cmd + ", building" + String.valueOf(i) + " BIGINT";
                }
                sql_cmd = sql_cmd + ")";
                Log.d(databaseTAG, "Init_Saved_Game: SQL_CMD = " + sql_cmd);
                //创建user表的格式
                db.execSQL(sql_cmd);
                break;
            }
        }
        Log.d(databaseTAG, "table \"user\" created ");
        cursor_for_sqlmaster.close();
        Log.d(databaseTAG, "cursor_for_sqlmaster is closed ");
        //完成user表的创建
    }

    public boolean check_saved_file(){
        SQLiteDatabase db = databaseHelper.getDataBase();
        String databaseTAG = "dbhelper.make_save_file";


        Cursor cursor_for_sqlmaster = db.query("sqlite_master", null, null, null, null, null, null);


        String sql_cmd = "";
        Boolean sql_is_empty = cursor_for_sqlmaster.moveToFirst();
        while (!cursor_for_sqlmaster.getString(1).equals("user")) {
            Log.d(databaseTAG, "searching sqlite_master... " + cursor_for_sqlmaster.getString(1));
            if (!cursor_for_sqlmaster.moveToNext()) {
                return false;
            }
        }
        return true;
//        Log.d(databaseTAG, "table \"user\" created ");
//        cursor_for_sqlmaster.close();
//        Log.d(databaseTAG, "cursor_for_sqlmaster is closed ");

    }

}
